<?php

/*
 *
 */

class Model_Mediate_Case extends Model_BaseModel
{
    use Lib_BaseTraits;

    /**
     * 缓存前缀
     *
     * @var unknown
     */
    private static $tag = 'Model_Mediate_Case';
    /**
     * Undocumented variable.
     *
     * @var string
     */
    private $table = 'cases';

    public function __construct()
    {
        // 选择连接的数据库
        parent::_init('mediation');
    }

    /**添加
     * @param $insertdata
     * @return mixed
     */
    public function insert($case, $litigant, $case_operation_log_arr, $attach)
    {
        $this->dao->conn(false);
        $this->dao->noCache();
        $this->dao->beginTransaction();

        //添加案件
        $data = array();
        $sql = 'INSERT INTO `cases`(';
        $sql .= '`' . implode('`,`', array_keys($case)) . '`';
        $sql .= ')VALUES(:' . implode(',:', array_keys($case)) . ')';
        foreach ($case as $key => $value) {
            $data[':' . $key] = $value;
        }
        $case_id = $this->dao->preparedSql($sql, $data)->lastInsertId();
        if (!$case_id) {
            $this->dao->rollback();
            return false;
        }

        //案件被告库
        $sql = "INSERT INTO case_litigant
		(`caseId`,`litigantName`,`cardId`,`telephone`,`type`)
		VALUES ";
        $str = '';
        $saveData = [];
        foreach ($litigant as $i => $val) {
            $str .= ',(' . ':caseId' . $i . ',' . ':litigantName' . $i . ',' . ':cardId' . $i . ',' . ':telephone' . $i . ',' . ':type' . $i . ')';
            $saveData[':caseId' . $i] = $case_id;
            //$saveData[':defendant_name'.$i] = Lib_infoAes::getInstance()->aesEncrypt($val['defendant_name']);
            $saveData[':litigantName' . $i] = ($val['litigantName']);
            $saveData[':type' . $i] = empty($val['type']) ? 2 : 1;
            $saveData[':cardId' . $i] = $val['cardId'];
            $saveData[':telephone' . $i] = $val['telephone'];
        }

        $sql = $sql . trim($str, ',');
        $respondent_res = $this->dao->preparedSql($sql, $saveData)->lastInsertId();
        if (!$respondent_res) {
            $this->dao->rollback();
            return false;
        }

        if (!empty($case_operation_log_arr)) {
            $case_operation_log_arr['caseId'] = $case_id;
            $data = array();
            $sql = 'INSERT INTO `case_operation_log`(';
            $sql .= '`' . implode('`,`', array_keys($case_operation_log_arr)) . '`';
            $sql .= ')VALUES(:' . implode(',:', array_keys($case_operation_log_arr)) . ')';
            foreach ($case_operation_log_arr as $key => $value) {
                $data[':' . $key] = $value;
            }
            $case_info_res = $this->dao->preparedSql($sql, $data)->affectedCount();
            if (!$case_info_res) {
                $this->dao->rollback();
                return false;
            }
        }
        if (!empty($attach)) {
            $data = array();
            $sql = 'INSERT INTO `case_attach` (`caseId`,`attachInfo`) VALUES(:caseId,:attachInfo)';
            $data[':caseId'] = $case_id;
            $data[':attachInfo'] = json_encode($attach);
            $case_info_res = $this->dao->preparedSql($sql, $data)->affectedCount();
            if (!$case_info_res) {
                $this->dao->rollback();
                return false;
            }
        }
        $this->dao->commit();
        $this->dao->clearTag(self::$tag);
        $this->dao->clearTag('Model_Mediate_Case');
        return true;
    }

    public function saveByIds($updateDta, $ids, $where = [])
    {
        $data = [];
        $sql = 'UPDATE `cases` SET ';
        $sqlarr = array();
        foreach ($updateDta as $key => $value) {
            if(strstr($value,'CONCAT(')){
                array_push($sqlarr, "`{$key}`={$value}");
            }else{
                array_push($sqlarr, "`{$key}`=:$key");
                $data[":$key"] = $value;
            }
        }
        $where_str = '';
        if (!empty($where)) {
            $where_str = 'AND '.implode(' AND ', $where);
        }
        $sql .= implode(',', $sqlarr);
        $sql .= " WHERE id in ({$ids}) {$where_str}";
        $res = $this->dao->conn(false)->noCache()->preparedSql($sql, $data)->affectedCount();
        $this->dao->clearTag(self::$tag);
        return $res;
    }


    /**
     * @desc 通过id查看案件详情
     *
     * @param int $id
     *
     * @return bool
     */
    public function getCaseIdByName($name)
    {
        $sql = "SELECT caseId FROM case_litigant WHERE litigantName=:litigantName";
        $res = $this->dao->conn()->setTag(self::$tag)->preparedSql($sql, array(':litigantName' => $name))->fetchAll();
        return empty($res) ? [] : array_column($res, 'caseId');

    }

    /**
     * 获取全部数据.
     *
     * @return array
     */
    public function countBySearch($search)
    {
        $search_str = 'WHERE 1 ';
        if (isset($search['where']) && !empty($search['where'])) {
            foreach($search['where'] as $where){
                if(strpos($where,'updateTime') !== false){
                    $search_str .= ' AND '.$where;
                }else{
                    $search_str .= ' AND '.$where;
                }
            }
        }
        $sql = "SELECT sum(debtTotal) as sumqkze,sum(debtAmount) as sumqkbj  FROM cases {$search_str} ";
        $res = $this->dao->conn()->setTag(self::$tag)->preparedSql($sql, [])->fetchAll();
        return  empty($res) ? $res : $res[0];
    }

    //获取数据通过变化的条件
    public function getDataByChangeWhere($where)
    {
        $sql = "SELECT id FROM {$this->table} WHERE {$where}";
        $res = $this->dao->conn()->setTag(self::$tag)->preparedSql($sql, array())->fetchAll();

        return $res;
    }

    public function updateStatusAddLogById($case_data, $log_info)
    {
        $this->dao->conn(false);
        $this->dao->noCache();
        $this->dao->beginTransaction();
        // 更新case状态
        if (empty($case_data) || !$case_data['id']) {
            return false;
        }
        $caseId = $case_data['id'];
        unset($case_data['id']);
        $data = [];
        $sql = 'UPDATE `cases` SET ';
        $sqlarr = array();
        foreach ($case_data as $key => $value) {
            array_push($sqlarr, "`{$key}`=:$key");
            $data[":$key"] = $value;
        }
        $sql .= implode(',', $sqlarr);
        $sql .= ' WHERE id=:id';
        $data[':id'] = $caseId;
        $update_res = $this->dao->preparedSql($sql, $data)->affectedCount();
        if (!$update_res) {
            $this->dao->rollback();

            return false;
        }
        if ($log_info) {
            // 插入案件历史操作记录表
            $sql = 'INSERT INTO `case_operation_log` (caseId,status,operationUid,operationName,operationContent,remark,createTime) VALUES (:caseId,:status,:operationUid,:operationName,:operationContent,:remark,:createTime)';

            $data = [
                ':caseId' => $log_info['caseId'],
                ':status' => isset($log_info['status']) ? $log_info['status'] : $case_data['caseStatus'],
                ':operationUid' => $log_info['operationUid'],
                ':operationName' => $log_info['operationName'],
                ':operationContent' => $log_info['operationContent'],
                ':remark' => $log_info['remark'],
                ':createTime' => time(),
            ];
            $retId = $this->dao->preparedSql($sql, $data)->lastInsertId();
            if (!$retId) {
                $this->dao->rollback();

                return false;
            }
        }
        $this->dao->commit();
        $this->dao->clearTag(self::$tag);

        return true;
    }
    public function updateTodayContactStutus(){
        $sql =  "UPDATE `cases` SET todayContactStutus = 1 where todayContactStutus in (2,3)";
        return  $this->dao->conn(false)->noCache()->preparedSql($sql, [])->affectedCount();
    }
    public function updateNextTime(){
        $time = time();
        $sql =  "UPDATE `cases` SET nextTime = 0 where todayContactStutus = 3 and nextTime > 0 and nextTime < $time";
        return  $this->dao->conn(false)->noCache()->preparedSql($sql, [])->affectedCount();
    }
}
